package com.anhry.app.safety.manage.system.struts.inteceptor;

import com.anhry.app.safety.manage.system.bean.TbUser;
import com.anhry.app.safety.manage.system.service.SystemService;
import com.anhry.app.safety.util.Util;
import com.anhry.app.safety.util.bean.Permission;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

/**
 * @date:2012-5-16
 * @remark: 判断用户是否拥有某一项功能的拦截器
 * @author:anhry
 */
public class PermissionInterceptor implements Interceptor {
	private static final long serialVersionUID = 1L;
	
	@Resource
	private SystemService systemService;

	public SystemService getSystemService() {
		return systemService;
	}

	public void setSystemService(SystemService systemService) {
		this.systemService = systemService;
	}

	public void destroy() {
	}

	public void init() {
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		ActionProxy proxy = invocation.getProxy();
		String methodName = proxy.getMethod();
		if (methodName == null) {
			methodName = "execute";
		}
		Method method = invocation.getAction().getClass().getMethod(methodName,new Class[0]);
		if (!validate(method)) {
			ActionContext.getContext().put("tip", "您没有执行该操作的权限");
			return "tips";
		}
		return invocation.invoke();
	}

	private boolean validate(Method method) {
		try {
			if ((method != null) && (method.isAnnotationPresent(Permission.class))) {
				HttpServletRequest request = ServletActionContext.getRequest();
				Permission permission = (Permission) method.getAnnotation(Permission.class);
				TbUser user = (TbUser)request.getSession().getAttribute(Util.SESSION_ADMINUSER);
				return (user != null) && (this.systemService.hasPermissionByFunCode(user, permission.module(),permission.permissionVaule()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}
